<script setup lang="ts">
import { createImageViewer } from '@/components/ImageViewer'
import { filingCabinetApi } from '@/api/customer'
import { uploadFilingcabinetApi, filingFieldEnumApi, deleteFilingcabinetApi } from '@/api/order'
const { t } = useI18n()
const { push } = useRouter()

const {
  source, // 来源
  orderId, //订单id
  customerId, // 客户id
  currentRow // 当前行
} = defineProps({
  source: {
    type: String,
    default: ''
  },
  orderId: {
    type: Number,
    default: 0
  },
  customerId: {
    type: Number,
    default: 0
  },
  currentRow: {
    type: Object,
    default: () => {}
  }
})

// 移动端检测
import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()
const isMobile = computed(() => appStore.getMobile)

// 定义 dataList 变量
const dataList = ref<any[]>([])
const getData = async () => {
  try {
    const res = await filingCabinetApi({
      order_id: orderId ? String(orderId) : '',
      customer_id: customerId ? String(customerId) : ''
    })
    dataList.value = res.data.list
  } catch (e) {}
}
//获取枚举
const optionSet = ref<any[]>([])
const fileTypeList = ref<any[]>([])
const getDropDownBoxInfo = async () => {
  try {
    const resp = await filingFieldEnumApi({ field: 'all' })
    optionSet.value = resp?.data.file_type
    if (source === 'customer') {
      fileTypeList.value = optionSet.value.filter((v) => v.value != 10 && v.value != 20)
      selectedId.value = fileTypeList.value[0].value
    } else {
      fileTypeList.value = optionSet.value.filter((v) => v.value != 10)
    }
  } catch (e) {}
}
onMounted(() => {
  getData()
  getDropDownBoxInfo()
})
//上传成功以后回调
const fileObj = ref<any>(null)
const handleUploadCallback = (val: any) => {
  fileObj.value = val
}

const handleRemoveFile = (val: any) => {
  fileObj.value = null
}

// 删除文件柜中的文件
const handleDeleteFile = async (row: any) => {
  try {
    await ElMessageBox.confirm(t('common.message.delete'), t('action.action'), {
      confirmButtonText: t('common.ok'),
      cancelButtonText: t('common.cancel'),
      type: 'warning'
    })

    const resp = await deleteFilingcabinetApi(row.id)
    if (resp.code === 0) {
      ElMessage.success(t('common.deleteSucMsg'))
      getData() // 重新获取数据
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文件失败:', error)
      ElMessage.error(t('common.failed'))
    }
  }
}

const handlePictureCardPreview = (url: any) => {
  try {
    if (!url) return
    if (/\.(jpg|jpeg|png|gif|bmp)$/i.test(url))
      return createImageViewer({
        urlList: [url]
      })
    window.open(url)
  } catch (error) {
    console.error('预览图片失败:', error)
  }
}
const dialogVisible = ref<boolean>(false)
const closeDialog = () => {
  dialogVisible.value = false
  fileObj.value = null
  selectedId.value = fileTypeList.value.length ? fileTypeList.value[0].value : ''
}
// 上传文件柜
const selectedId = ref<string | number>('')
const submit = async () => {
  try {
    // 表单验证
    if (!selectedId.value) {
      ElMessage.warning('请选择文件类型')
      return
    }
    if (!fileObj.value) {
      ElMessage.warning('请选择附件')
      return
    }

    // 构建请求参数
    const params = {
      file_type: selectedId.value,
      order_id: orderId,
      customer_id: customerId,
      file_id: fileObj.value.id,
      title: fileObj.value.name,
      order_type: source === 'customer' ? '' : source
    }

    // 发送请求
    const resp = await uploadFilingcabinetApi(params)

    if (resp.code === 0) {
      ElMessage.success('提交成功')
      closeDialog()
      getData()
    }
  } catch (error) {
    console.error('提交文件失败:', error)
  }
}

type imageType = {
  id: number
  url: string
  name: string
}
const previewVisible = ref(false)
const previewTitle = ref('')
const previewType = ref('')
const dialogFile = ref<imageType>({
  id: 0,
  url: '',
  name: ''
})
const fileExtensions = {
  image: ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg'],
  pdf: ['.pdf'],
  text: ['.txt', '.html', '.md']
}
// 判断文件是否可以预览
const isPreviewable = (fileUrl: string) => {
  const extension = fileUrl.slice(fileUrl.lastIndexOf('.')).toLowerCase()

  if (fileExtensions.image.includes(extension)) {
    return 'image'
  }
  if (fileExtensions.pdf.includes(extension)) {
    return 'pdf'
  }
  if (fileExtensions.text.includes(extension)) {
    return 'text'
  }
  return 'other' // 无法预览的文件类型
}
// 文件点击事件处理
const handleFileClick = (fileParams) => {
  const type = isPreviewable(fileParams.file_url)
  if (type === 'other') {
    // 如果文件不可预览，直接下载
    handleFileDownload(fileParams)
  } else {
    // 如果文件可预览，弹出预览框
    previewType.value = type
    previewTitle.value = fileParams.title
    previewVisible.value = true
    dialogFile.value.url = fileParams.file_url
  }
}

const handleFileDownload = async (fileParams) => {
  try {
    // 如果是图片文件，打开新标签页
    if (fileParams.file_url && fileParams.file_url.match(/\.(jpg|jpeg|png|gif|bmp)$/i)) {
      // 在新标签页中打开图片
      window.open(fileParams.file_url, '_blank')
    } else {
      // 对于其他文件类型，直接使用文件 URL进行下载
      const link = document.createElement('a')
      link.download = fileParams.title || 'download' // 设置文件名
      link.href = fileParams.file_url
      link.target = '_blank'
      link.click()
    }
  } catch (error) {
    console.error('Error handling file download or open:', error)
  }
}
// 关闭预览窗口
const handleClosePreview = () => {
  previewVisible.value = false
  previewType.value = '' // 重置文件类型
}
const checkOrder = (row: { order_type: any; order_id: any }) => {
  const path = ref<string>('') // 默认值为空字符串
  const query = reactive<{ [key: string]: string }>({}) // 默认值为空字符串
  switch (row.order_type) {
    case 'wholesal':
      path.value = `/order/wholesal-order-management/detail`
      push({ path: path.value, query: { id: row.order_id } })
      break
    case 'order':
      path.value = `/order/order-management/detail`
      push({ path: path.value, query: { id: row.order_id } })
      break
    default:
      path.value = ''
      break
  }
}
</script>

<template>
  <div class="file-cabinet-container">
    <el-button type="primary" @click="dialogVisible = true" class="upload-btn">
      {{ t('common.button.uploadFile') }}
    </el-button>

    <!-- 桌面端表格 -->
    <div v-if="!isMobile" class="desktop-table">
      <el-table
        :data="dataList"
        highlight-current-row
        stripe
        border
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ textAlign: 'center' }"
      >
        <el-table-column
          :label="t('wholesalOrder.name')"
          prop="title"
          min-width="300"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ row.title }}
          </template>
        </el-table-column>
        <el-table-column
          :label="t('supply.sup_type')"
          prop="file_type_value"
          width="200"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('customer.creator')"
          prop="creator_name"
          width="200"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('customer.create_time')"
          prop="create_time"
          width="200"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('order.orderCode')"
          min-width="300"
          :show-overflow-tooltip="true"
          v-if="source === 'customer'"
        >
          <template #default="{ row }">
            <el-link type="primary" @click="checkOrder(row)">
              {{ row.order_no }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column
          :label="t('action.action')"
          width="200"
          :show-overflow-tooltip="true"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleFileClick(row)">
              {{ t('common.button.preview') }}
            </el-button>
            <el-button type="success" size="small" @click="handleFileDownload(row)">
              {{ t('common.button.download') }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteFile(row)"
              v-if="currentRow.order_status != 20"
            >
              {{ t('action.del') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 移动端卡片列表 -->
    <div v-else class="mobile-card-container">
      <div v-for="row in dataList" :key="row.id" class="file-card pt-15px mobile-card">
        <div class="card-header">
          <div class="file-title" style="word-break: break-all; white-space: normal">{{
            row.title
          }}</div>
        </div>
        <div class="card-body">
          <div class="info-row">
            <span class="label">{{ t('supply.sup_type') }}:</span>
            <span class="value">{{ row.file_type_value }}</span>
          </div>
          <div class="info-row">
            <span class="label">{{ t('customer.creator') }}:</span>
            <span class="value">{{ row.creator_name }}</span>
          </div>
          <div class="info-row">
            <span class="label">{{ t('customer.create_time') }}:</span>
            <span class="value">{{ row.create_time }}</span>
          </div>
          <div v-if="source === 'customer'" class="info-row">
            <span class="label">{{ t('order.orderCode') }}:</span>
            <el-link type="primary" @click="checkOrder(row)" class="order-link">
              {{ row.order_no }}
            </el-link>
          </div>
          <div class="file-actions">
            <el-button @click="handleFileClick(row)" type="primary" size="small">{{
              t('common.button.preview')
            }}</el-button>
            <el-button @click="handleFileDownload(row)" type="success" size="small">{{
              t('common.button.download')
            }}</el-button>
            <el-button
              @click="handleDeleteFile(row)"
              type="danger"
              size="small"
              v-if="currentRow.order_status != 20"
            >
              {{ t('action.del') }}
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 上传对话框 -->
  <Dialog
    v-model="dialogVisible"
    :width="isMobile ? '95%' : '60%'"
    :title="t('wholesalOrder.selectShop')"
    :max-height="isMobile ? '90vh' : 700"
    :before-close="() => closeDialog()"
    class="upload-dialog mobile-dialog"
  >
    <div class="dialog-content">
      <div>
        <el-form-item :label="t('order.fileType')" :label-width="isMobile ? '80px' : '120px'">
          <el-select
            v-model="selectedId"
            :filterable="true"
            :placeholder="t('order.fileType')"
            :clearable="false"
            :size="isMobile ? 'default' : 'default'"
            style="width: 100%"
          >
            <el-option
              v-for="item in fileTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('supply.att_path')" :label-width="isMobile ? '80px' : '120px'">
          <UploadFile
            class="w-100%"
            url="/common/uploadFile"
            drag
            :file-type="['png', 'jpg', 'jpeg', 'bmp', 'pdf', 'docx', 'doc', 'xlsx', 'xls']"
            :params="{ directory: 12 }"
            :limit="1"
            :upload-file-button-name="t('common.clickUpload')"
            buttonWidth="100%"
            :button-link="true"
            :show-file-list="true"
            @upload-success-res="handleUploadCallback"
            @handle-remove-file="handleRemoveFile"
            @handle-picture-card-preview="handlePictureCardPreview"
          />
          <el-text class="text-sm" type="info">{{
            t('common.message.uploadExceed', { limit: 1 })
          }}</el-text>
        </el-form-item>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer mobile-button-group horizontal">
        <el-button
          class="footer-btn"
          @click="closeDialog()"
          :size="isMobile ? 'default' : 'default'"
        >
          {{ t('system.parameterConfig.cancel') }}
        </el-button>
        <el-button
          type="primary"
          @click="submit()"
          :size="isMobile ? 'default' : 'default'"
          class="footer-btn"
        >
          {{ t('order.confirm') }}
        </el-button>
      </div>
    </template>
  </Dialog>

  <!-- 预览对话框 -->
  <el-dialog
    v-model="previewVisible"
    :title="previewTitle"
    :width="isMobile ? '95%' : '80%'"
    :before-close="handleClosePreview"
    class="preview-dialog mobile-dialog"
  >
    <!-- 根据文件类型显示预览内容 -->
    <div v-if="previewType === 'image'" class="preview-content">
      <img :src="dialogFile?.url" alt="预览图片" class="preview-image" />
    </div>
    <div v-if="previewType === 'pdf'" class="preview-content">
      <iframe
        :src="dialogFile?.url"
        :style="{ width: '100%', height: isMobile ? '60vh' : '80vh' }"
        frameborder="0"
      ></iframe>
    </div>
    <div v-if="previewType === 'text'" class="preview-content">
      <iframe
        :src="dialogFile?.url"
        :style="{ width: '100%', height: isMobile ? '60vh' : '80vh' }"
        frameborder="0"
      ></iframe>
    </div>
    <div v-if="previewType === 'other'" class="preview-content">
      <p>无法预览此文件，您可以下载它。</p>
    </div>
  </el-dialog>
</template>
